package com.huizhonglm.diap.ui.views;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.core.storage.model.district.CityInfo;
import com.huizhonglm.diap.core.storage.model.district.DistInfo;
import com.huizhonglm.diap.core.storage.model.district.ProvInfo;
import com.huizhonglm.diap.core.utils.DistrictUtil;
import com.huizhonglm.diap.model.District;
import com.huizhonglm.diap.widget.pickerView.ArrayWheelAdapter;
import com.huizhonglm.diap.widget.pickerView.OnWheelScrollListener;
import com.huizhonglm.diap.widget.pickerView.WheelView;

import java.util.List;

/**
 * 城市地区选择
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2014-12-17 16:16
 */
public class CityPickerView extends PopupWindow {

    private View parent = null;
    private Activity mActivity = null;
    private WheelView provWheelView = null;
    private WheelView cityWheelView = null;
    private WheelView areaWheelView = null;

    private List<ProvInfo> provInfos;
    private List<CityInfo> cityInfos;
    private List<DistInfo> areaInfos;

    private String[] provArray = null;
    private String[] cityArray = null;
    private String[] areaArray = null;

    private OnDistrictSetListener mOnDistrictSetListener;

    private PopupMaskView mask;

    //是否含有全部选项（true：是， false：否）
    private final boolean hasAll = false;

    private boolean isOnScrolling = false;

    /**
     * 日期选择器
     *
     * @param activity 上下文
     * @param parent   显示锚点View
     * @param l        日期选择监听器
     */
    public CityPickerView(Activity activity, View parent, OnDistrictSetListener l) {
        super(activity);
        mask = new PopupMaskView(activity, this);
        this.parent = parent;
        this.mActivity = activity;
        this.mOnDistrictSetListener = l;
        initArrayData();
        initPickerView();
    }

    public void show(String provName, String cityName, String areaName) {
        mask.showAtLocation(parent);
        setDefaultSelected(provName, cityName, areaName);
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        }
    }

    /**
     * 弹出拨轮
     */
    public void show() {
        mask.showAtLocation(parent);
        setDefaultSelected(provArray[0], cityArray[0], areaArray[0]);
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        }
    }


    /**
     * 初始化滚轮数据
     */
    private void initArrayData() {
        // 省份数组
        provInfos = DistrictUtil.getInstance().getProvData();
        int size = provInfos.size();
        provArray = new String[size];
        for (int i = 0; i < size; i++) {
            provArray[i] = provInfos.get(i).getProvName();
        }
        // 城市数组
        cityArray = getCityArray(provArray[0]);
        // 区县数组
        areaArray = getAreaArray(cityArray[0]);
    }

    private String[] getCityArray(String provName) {
        if (!EmptyUtil.isEmpty(provName)) {
            ProvInfo prov = getProvInfo(provName);
            if (prov != null) {
                cityInfos = DistrictUtil.getInstance().getCityDataByProvId(prov.getProvId(), hasAll);
                int size = cityInfos.size();
                String[] cityArr = new String[size];
                for (int i = 0; i < size; i++) {
                    cityArr[i] = cityInfos.get(i).getCityName();
                }
                return cityArr;
            }
        }
        return null;
    }

    private String[] getAreaArray(String cityName) {
        if (!EmptyUtil.isEmpty(cityName)) {
            CityInfo city = getCityInfo(cityName);
            if (city != null) {
                areaInfos = DistrictUtil.getInstance().getDistDataByCityId(city.getCityId(), hasAll);
                int size = areaInfos.size();
                String[] areaArr = new String[size];
                for (int i = 0; i < size; i++) {
                    areaArr[i] = areaInfos.get(i).getDistName();
                }
                return areaArr;
            }
        }
        return null;
    }

    private ProvInfo getProvInfo(String provName) {
        if (!EmptyUtil.isEmpty(provInfos)) {
            for (ProvInfo prov : provInfos) {
                if (provName.equals(prov.getProvName())) {
                    return prov;
                }
            }
        }
        return null;
    }

    private CityInfo getCityInfo(String cityName) {
        if (!EmptyUtil.isEmpty(cityInfos)) {
            for (CityInfo city : cityInfos) {
                if (cityName.equals(city.getCityName())) {
                    return city;
                }
            }
        }
        return null;
    }

    private DistInfo getAreaInfo(String areaName) {
        if (!EmptyUtil.isEmpty(areaInfos)) {
            for (DistInfo area : areaInfos) {
                if (areaName.equals(area.getDistName())) {
                    return area;
                }
            }
        }
        return null;
    }


    private int getCurrCityIndex() {
        int currIndex = cityWheelView.getCurrentItem();
        if (currIndex <= cityArray.length - 1) {
            return currIndex;
        }
        return cityArray.length - 1;
    }

    private int getCurrAreaIndex() {
        int currIndex = areaWheelView.getCurrentItem();
        if (currIndex <= areaArray.length - 1) {
            return currIndex;
        }
        return areaArray.length - 1;
    }

    /**
     * 初始化pickerView
     */
    private void initPickerView() {
        View contentView = View.inflate(mActivity, R.layout.view_city_picker, null);
        provWheelView = (WheelView) contentView.findViewById(R.id.year_whellView);
        cityWheelView = (WheelView) contentView.findViewById(R.id.month_wheelView);
        areaWheelView = (WheelView) contentView.findViewById(R.id.day_whellView);
        Button confirmBtn = (Button) contentView.findViewById(R.id.common_btn);
        Button cancelBtn = (Button) contentView.findViewById(R.id.cancel_btn);
        contentView.setFocusableInTouchMode(true);
        contentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && (isShowing())) {
                    dismiss();
                    return true;
                }
                return false;
            }
        });
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOnScrolling) {
                    dismiss();
                    ProvInfo prov;
                    CityInfo city;
                    DistInfo area;
                    String provName = provArray[provWheelView.getCurrentItem()];
                    prov = getProvInfo(provName);
                    String cityName = cityArray[cityWheelView.getCurrentItem()];
                    city = getCityInfo(cityName);
                    String areaName = areaArray[areaWheelView.getCurrentItem()];
                    area = getAreaInfo(areaName);
                    if (city != null && prov != null && area != null) {
                        if ("9999999".equals(city.getCityCode()) || "9898989".equals(area.getDistId())){
                            if (mOnDistrictSetListener != null) {
                                mOnDistrictSetListener.onDistrictSet(prov, city, area);
                            }
                        } else {
                            District district = DistrictUtil.getInstance().getDistrict(area.getDistId());
                            if (district != null) {
                                prov = new ProvInfo();
                                prov.setProvId(district.getProvId());
                                prov.setProvName(district.getProvName());
                                city = new CityInfo();
                                city.setProvId(district.getProvId());
                                city.setCityCode(district.getCityCode());
                                city.setCityName(district.getCityName());
                                city.setCityCode(district.getCityCode());
                                if (mOnDistrictSetListener != null) {
                                    mOnDistrictSetListener.onDistrictSet(prov, city, area);
                                }
                            }
                        }
                    }
                }
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOnScrolling) {
                    dismiss();
                }
            }
        });

        provWheelView.setAdapter(new ArrayWheelAdapter<>(provArray));
        provWheelView.setLabel("");
        provWheelView.addScrollingListener(getScrollListener());

        cityWheelView.setAdapter(new ArrayWheelAdapter<>(cityArray));
        cityWheelView.setLabel("");
        cityWheelView.addScrollingListener(getScrollListener());

        areaWheelView.setAdapter(new ArrayWheelAdapter<>(areaArray));
        areaWheelView.setLabel("");
        areaWheelView.addScrollingListener(getScrollListener());

        setFocusable(true);
        setWheelColumnNum(3);
        setContentView(contentView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setBackgroundDrawable(new BitmapDrawable());
        setAnimationStyle(R.style.bottom_view_anim_style);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                mask.dismiss();
            }
        });
        update();
    }

    private OnWheelScrollListener getScrollListener() {
        return new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
                isOnScrolling = true;
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                if (!wheel.equals(areaWheelView)) {
                    String provName = provArray[provWheelView.getCurrentItem()];
                    cityArray = getCityArray(provName);
                    cityWheelView.setAdapter(new ArrayWheelAdapter<>(cityArray));
                    cityWheelView.setCurrentItem(getCurrCityIndex());
                    String cityName = cityArray[cityWheelView.getCurrentItem()];
                    areaArray = getAreaArray(cityName);
                    areaWheelView.setAdapter(new ArrayWheelAdapter<>(areaArray));
                    areaWheelView.setCurrentItem(getCurrAreaIndex());
                }
                isOnScrolling = false;
            }
        };
    }

    private void setWheelColumnNum(int columnNum) {
        if (provWheelView != null && cityWheelView != null && areaWheelView != null) {
            provWheelView.setColumnNum(columnNum);
            cityWheelView.setColumnNum(columnNum);
            areaWheelView.setColumnNum(columnNum);
        }
    }

    private void setDefaultSelected(String provName, String cityName, String areaName) {
        if (!EmptyUtil.isEmpty(provName)) {
            cityArray = getCityArray(provName);
            cityWheelView.setAdapter(new ArrayWheelAdapter<>(cityArray));
            cityWheelView.setCurrentItem(getCurrCityIndex());
            boolean isContainsMonth = false;
            for (String cn : cityArray) {
                if (cn.equals(cityName)) {
                    isContainsMonth = true;
                    break;
                }
            }
            if (!isContainsMonth) {
                cityName = cityArray[0];
            }
            areaArray = getAreaArray(cityName);
            areaWheelView.setAdapter(new ArrayWheelAdapter<>(areaArray));
            areaWheelView.setCurrentItem(getCurrAreaIndex());
            boolean isContainsDay = false;
            for (String an : areaArray) {
                if (an.equals(areaName)) {
                    isContainsDay = true;
                    break;
                }
            }
            if (!isContainsDay) {
                areaName = areaArray[0];
            }

            int indexOfProv = 0;
            int indexOfCity = 0;
            int indexOfArea = 0;
            if (!EmptyUtil.isEmpty(provName)) {
                int i = 0;
                for (String pn : provArray) {
                    if (pn.equals(provName)) {
                        indexOfProv = i;
                        break;
                    }
                    i++;
                }
            }

            if (!EmptyUtil.isEmpty(cityName)) {
                int j = 0;
                for (String cn : cityArray) {
                    if (cn.equals(cityName)) {
                        indexOfCity = j;
                        break;
                    }
                    j++;
                }
            }

            if (!EmptyUtil.isEmpty(areaName)) {
                int k = 0;
                for (String an : areaArray) {
                    if (an.equals(areaName)) {
                        indexOfArea = k;
                        break;
                    }
                    k++;
                }
            }
            provWheelView.setCurrentItem(indexOfProv);
            cityWheelView.setCurrentItem(indexOfCity);
            areaWheelView.setCurrentItem(indexOfArea);
        } else {
            provWheelView.setCurrentItem(0);
            cityWheelView.setCurrentItem(0);
            areaWheelView.setCurrentItem(0);
        }
    }

    /**
     * 确认所选择的数据
     *
     * @author LiXiaoLong
     * @version 1.0
     * @since 2013年7月30日 下午1:13:38 (1.0)
     */
    public interface OnDistrictSetListener {
        /**
         * @param prov 省份信息
         * @param city 城市信息
         * @param dist 地区信息
         */
        void onDistrictSet(ProvInfo prov, CityInfo city, DistInfo dist);
    }
}